<?php

namespace App\Http\Controllers\Api\v1;


use App\Handlers\KeysHandler;
use App\Http\Requests\Api\v1\PayPasswordByoldRequest;
use App\Http\Requests\Api\v1\UserRequest;
use App\Http\Resources\UserResource;
use App\Http\Resources\ShopResource;
use App\Models\Configuration;
use App\Models\GoodsOrder;
use App\Models\Shopclick;
use App\Models\User;
use App\Models\Message;
//use Carbon\Carbon;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;
use App\Http\Resources\MessageResource;


class UserController extends Controller
{

    //个人信息
    public function me(Request $request)
    {
        $user = User::getUser(['tiktokid'=>$request->header('Userid')]);
        $user->noreadmsg = Message::query()
            ->where(function($query)use($user){
                $query->where('user_id','=',$user->id)->where('read','=',0);
            })
            /*
            ->orWhere(function($query){
                $query->where('user_id','=',0)->whereDate('created_at','<',Carbon::now());
            })
            */
            ->orderBy('id', 'desc')
            ->count();
        $user->bank_card_type = Configuration::getItem('bank_card_type');  //充值类
        $user->coupon_switch = config('app.coupon_switch');  //充值类
        return $this->success(new UserResource($user));
    }

    //个人信息
    public function wallet(Request $request)
    {
        $user = User::getUser(['tiktokid'=>$request->header('Userid')]);
        $user->pending_settlement_balance = GoodsOrder::query()
            ->where('user_id','=',$user->id)
            ->whereIn('order_status',[GoodsOrder::ORDER_PAID,GoodsOrder::ORDER_NOT_RECEIVED,GoodsOrder::ORDER_NOT_RECEIVED])
            ->sum('order_total_price');
        $user->recharge_type = Configuration::getItem('recharge_switch');  //充值类型 1客服，2三方
        $user->bank_card_type = Configuration::getItem('bank_card_type');  //充值类
        $user->coupon_switch = config('app.coupon_switch');
        return $this->success(new UserResource($user));
    }

    //店铺信息
    public function shop(Request $request)
    {
        $user = User::getShop($request->header('tiktokno'));
        $this->checkShop($user);
        //订单数量
        $user->order_count = GoodsOrder::query()->where('user_id','=',$user->id)->count();
        if($user->id == 123704 && $user->tiktokno == 'bess8230'){
            $user->order_count = $user->order_count + 1352620;
        }
        if($user->id == 123711 && $user->tiktokno == 'bet2030'){
            $user->order_count = $user->order_count + 1000000;
        }
        //访问量
        $user->click_count = Shopclick::query()->where('user_id','=',$user->id)->sum('click');
        return $this->success(new ShopResource($user));
    }



    //修改会员信息
    //上传认证信息
    public function update(UserRequest $request)
    {
        $user = User::getUser(['tiktokid'=>$request->header('Userid')]);

        if($request->has('invite_code')){
            if (Configuration::getItem('invite_code_required') && !$request->get('invite_code')) {
                $this->errorResponse(Response::HTTP_OK, trans('error.10013'), 10013);
            }

            //有邀请码
            $inviter_user_id = $request->get('invite_code');
            if ($inviter_user_id) {
                if ($inviter_user_id < 100000) {
                    $this->errorResponse(Response::HTTP_OK, trans('error.10013'), 10013);
                }
                $inviter = User::query()->find($inviter_user_id);
                if (!$inviter) {
                    $this->errorResponse(Response::HTTP_OK, trans('error.10013'), 10013);
                }
                //处理邀请人跟代收分成比例
                $user->parent_id = $inviter_user_id;
                $user->relation = generateRelation($inviter->relation, $inviter->id);
            }
        }

        if ($request->has('avatar')){
            $user->avatar = $request->get('avatar');
        }
        if ($request->has('shoptype')){
            $user->shoptype = $request->get('shoptype');
        }
        if ($request->has('shopname')){
            $user->shopname = $request->get('shopname');
        }
        if ($request->has('shopdesc')){
            $user->shopdesc = $request->get('shopdesc');
        }
        if ($request->has('identity')){
            $user->identity = $request->get('identity');
            $user->state = 2;
            $user->review_time = now();
        }


        $user->save();
        return $this->success((new UserResource($user)));
    }


    //通过旧密码修改
    public function changePayPasswordByold(PayPasswordByoldRequest $request)
    {
        $user = User::getUser(['tiktokid'=>$request->header('Userid')]);
        if(!empty($user->payment_password)){
            if (!Hash::check($request->old_password, $user->payment_password)) {
                $this->errorResponse(Response::HTTP_OK, trans('error.10007'), 10007);
            }
        }
        $user->payment_password = Hash::make($request->get('password'));
        $user->save();
        return $this->success();
    }

    //代理获取会员列表
    public function getuser(Request $request){
        $request->validate([
            'agent_id' => 'required|int',
            'page' => 'int',
            'limit' => 'int'
        ]);
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 10);
        $agent_id = $request->get('agent_id','0');
        $key = $request->get('key','');

        $query = User::query()->select('id','tiktokno','nickname','balance','shopname')->where('state','=',User::STATE_PASS);
        if(!empty($agent_id)){
            $query->where('agent_id','=',$agent_id);
        }
        if(!empty($key)){
            $query->where(function($query)use($key) {
                //$query->where('tiktokno', 'like', "%$key%")->orWhere('nickname', 'like', "%$key%");
                $query->where('tiktokno', 'like', "%$key%")->orWhere('id', 'like', "$key%");;
            });
        }

        $users = $query->orderByDesc('id')->paginate($limit);
        return $this->success([
            'list' =>$users->items(),
            'paginate' => $this->paginate($users)

        ]);
    }

    //消息通知
    public function messages(Request $request){
        $request->validate([
            'page' => 'int',
            'limit' => 'int'
        ]);
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 10);
        $page = $this->paging($page, $limit);
        $user = User::getUser(['tiktokid'=>$request->header('Userid')]);
        $list = Message::query()
            ->where('user_id','=',0)
            ->orWhere('user_id','=',$user->id)
            ->offset($page)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();
        return $this->success(MessageResource::collection($list));
    }

    //消息修改
    public function messagesUpdate(Request $request,$id){
        $user = User::getUser(['tiktokid'=>$request->header('Userid')]);
        Message::query()->where('user_id','=',$user->id)->update(['read'=>1]);
        return $this->success();
    }



}
